/*
 * Copyright (c) 2020-2021 Siddharth Chandrasekaran <sidcha.dev@gmail.com>
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <string.h>

#include "sevenbox/base/circbuf_var.h"
#include "sevenbox/base/types.h"


int circbuf_pop(circbuf_t *circ_buf, void *elem, int read_only)
{
	int total;
	char *tail;
	int elem_size = 0;

	total = circ_buf->push_count - circ_buf->pop_count;
	if (total < 0)
		total += (2 * circ_buf->size);

	if (total == 0)
		return -1; // Empty

	tail = (char *)circ_buf->buffer + ((circ_buf->pop_count % circ_buf->size)
			* circ_buf->element_size);

	if (elem)
		memcpy(elem, tail, circ_buf->element_size);

	if (!read_only) {
#ifdef CRICBUF_CLEAN_ON_POP
		memset(tail, 0, circ_buf->element_size);
#endif
		circ_buf->pop_count++;
		if (circ_buf->pop_count >= (2*circ_buf->size))
			circ_buf->pop_count = 0;
	}
	return 0;
}

/**
 * @brief 
 * 
 * @param circ_buf 
 * @param elem : 第一个字节表示数据长度
 * @return int 
 */
int circbuf_push(circbuf_var_t *circ_buf, void *elem)
{
	int total;
	char *head;
	circbuf_var_elem_header_t *header = (circbuf_var_elem_header_t*)elem;

	//判断空间是否足够
	
	return 0;
}

int circbuf_free_space(circbuf_t *circ_buf)
{
	int total;

	total = circ_buf->push_count - circ_buf->pop_count;
	if (total < 0)
		total += (2 * circ_buf->size);

	return circ_buf->size - total;
}

int circbuf_counts(circbuf_t *circ_buf)
{
	int total;

	total = circ_buf->push_count - circ_buf->pop_count;
	if (total < 0)
		total += (2 * circ_buf->size);

	return total;
}
